package com.uniflow.config;

import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * 请求ID拦截器
 * 为每个请求生成唯一的请求ID，用于日志追踪
 * 
 * @author uniflow
 * @since 1.0.0
 */
@Component
public class RequestIdInterceptor implements HandlerInterceptor {
    
    private static final String REQUEST_ID_HEADER = "X-Request-ID";
    private static final String REQUEST_ID_MDC_KEY = "requestId";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头获取请求ID，如果没有则生成新的
        String requestId = request.getHeader(REQUEST_ID_HEADER);
        if (requestId == null || requestId.trim().isEmpty()) {
            requestId = generateRequestId();
        }
        
        // 设置到响应头
        response.setHeader(REQUEST_ID_HEADER, requestId);
        
        // 设置到MDC，用于日志记录
        MDC.put(REQUEST_ID_MDC_KEY, requestId);
        
        // 设置到请求属性，供后续使用
        request.setAttribute(REQUEST_ID_MDC_KEY, requestId);
        
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                               Object handler, Exception ex) {
        // 清理MDC
        MDC.remove(REQUEST_ID_MDC_KEY);
    }
    
    /**
     * 生成请求ID
     */
    private String generateRequestId() {
        return "req_" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
    }
}